<template>
	<div class="w-full">
		<!-- 折叠面板 -->
		<el-collapse 
			v-model="activeCollapse" 
			class="border-none shadow-none"
		>
			<el-collapse-item 
				:title="title" 
				name="confirmForm" 
				class="!border !border-gray-200 dark:!border-gray-700 !rounded-lg !mb-4 !overflow-hidden transition-all duration-300 hover:!border-blue-400 dark:hover:!border-blue-500"
				:class="{ '!border-blue-500 dark:!border-blue-400': activeCollapse.includes('confirmForm') }"
			>
				<template #title>
					<div class="flex items-center gap-3 py-1">
						<!-- 表单图标 -->
						<div class="flex-shrink-0 w-8 h-8 bg-blue-50 dark:bg-blue-900/30 rounded-lg flex items-center justify-center">
							<svg
								xmlns="http://www.w3.org/2000/svg"
								class="w-4 h-4 text-blue-600 dark:text-blue-400"
								fill="none"
								viewBox="0 0 24 24"
								stroke="currentColor"
							>
								<path
									stroke-linecap="round"
									stroke-linejoin="round"
									stroke-width="2"
									d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
								/>
							</svg>
						</div>
						
						<!-- 标题区域 -->
						<div class="flex-1 flex items-center justify-between">
							<span class="font-semibold text-gray-800 dark:text-gray-200 text-sm">{{ title }}</span>
							<div class="flex items-center gap-2">
								<!-- 已提交标签 -->
								<el-tag 
									v-if="isSubmitted" 
									type="success" 
									size="small" 
									class="!bg-green-50 !text-green-700 !border-green-200 dark:!bg-green-900/30 dark:!text-green-400 dark:!border-green-700/50"
								>
									<div class="flex items-center gap-1">
										<svg class="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
											<path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd"/>
										</svg>
										已提交
									</div>
								</el-tag>
							</div>
						</div>
					</div>
				</template>
				<!-- 表单渲染区域 -->
				<div class="mx-4 bg-gray-50 dark:bg-gray-800/50 rounded-lg border border-gray-100 dark:border-gray-700/50 overflow-hidden">
					<!-- 表单内容区域 -->
					<div class="p-4">
						<div 
							:style="{ height: designerHeight }" 
							class="overflow-y-auto custom-scrollbar"
						>

							<el-form label-position="top" v-if="rule.length > 0" class="space-y-4">
								<FormCreate :rule="rule" v-model="formData" v-model:api="fApi" :option="options" />
							</el-form>
							
							<!-- 加载状态 -->
							<div v-else class="flex flex-col items-center justify-center h-full min-h-[200px] text-gray-500 dark:text-gray-400">
								<div class="animate-spin w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full mb-3" v-if="loadingText.includes('加载')"></div>
								<svg v-else class="w-12 h-12 text-gray-300 dark:text-gray-600 mb-3" fill="currentColor" viewBox="0 0 20 20">
									<path fill-rule="evenodd" d="M3 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z" clip-rule="evenodd"/>
								</svg>
								<p class="text-sm">{{ loadingText }}</p>
							</div>
						</div>
					</div>
				</div>
			</el-collapse-item>
		</el-collapse>
	</div>
</template>

<script lang="ts" setup>
import FcDesigner from 'form-create-designer';
import FormCreate from '/@/views/flow/workflow/components/FormCreate.vue';
import { Api, Rule } from '@form-create/element-ui';
import { useMessage } from '/@/hooks/message';
import { submitAiFunc } from '/@/api/knowledge/aiGen';
import { ChatMessage } from '../ts';
import { Local } from '/@/utils/storage';

interface Props {
	message: ChatMessage; // 直接接收 message 对象
	title?: string;
	height?: string;
}

interface FormDataType {
	[key: string]: any;
}

const props = withDefaults(defineProps<Props>(), {
	title: '确认表单',
	height: '400px'
});

const emit = defineEmits<{
	confirm: [formData: any];
	cancel: [];
}>();

const message = useMessage();

// FormCreate 相关
const fApi = ref<Api>();
const formData = ref<FormDataType>({});
const rule = ref<any[]>([]);
const confirmLoading = ref(false);
const loadingText = ref('正在加载表单...');
const submitBtn = ref(true);

// 折叠面板相关
const activeCollapse = ref<string[]>(['confirmForm']); // 默认展开
const isSubmitted = ref(false); // 是否已提交标记

// 计算设计器高度
const designerHeight = computed(() => {
	return props.height;
});

// FormCreate 全局配置选项
const options = computed(() => ({
	onSubmit: async (formData: any) => {
		try {
			confirmLoading.value = true;
			
			// 调用后台 API 提交数据
			const submitData = {
				funcName: props.message.functionName,
				...formData
			};
			
			const { data } = await submitAiFunc(submitData);

			// 提交成功后隐藏 submitBtn
			submitBtn.value = false;
			
			// 标记为已提交并折叠面板
			isSubmitted.value = true;
			activeCollapse.value = []; // 折叠面板
			emit('confirm', data);
			message.success('表单提交成功');
			Local.set('isSubmitted'+props.message.messageKey, true);
		} catch (error: any) {
			message.error(error?.data?.message || '表单提交失败，请重试');
		} finally {
			confirmLoading.value = false;
		}
	},
	formData: formData.value,
	submitBtn: {
		loading: confirmLoading.value,
		innerText: '确认提交',
		show: submitBtn.value && !isSubmitted.value
	}
}));

// 解析并设置表单规则 - 参考 startFlow.vue 的实现
const parseAndSetFormRule = () => {
	try {
		if (props.message?.confirmForm) {
			loadingText.value = '正在解析表单...';
			
      let formRule: any;
      formRule = props.message.confirmForm;

			// 使用 FcDesigner.formCreate.parseJson 解析表单项，类似 startFlow.vue
			const parsedFormItems = FcDesigner.formCreate.parseJson(formRule);
			rule.value = parsedFormItems;
			loadingText.value = '表单加载完成';
		} else {
			loadingText.value = '暂无表单数据';
		}
	} catch (error) {
		message.error('表单数据格式错误');
		loadingText.value = '表单加载失败';
	}
};



// 组件挂载后设置表单规则
onMounted(() => {
	nextTick(() => {
		isSubmitted.value = Local.get('isSubmitted' + props.message.messageKey) || false;

		if (isSubmitted.value) {
			activeCollapse.value = [];
		}
		parseAndSetFormRule();

	});
});

// 监听 props 变化，更新表单规则
watch(
	() => props.message?.confirmForm,
	() => {
		nextTick(() => {
			parseAndSetFormRule();
		});
	}
);

watch(
	() => isSubmitted.value,
	() => {
		console.log('isSubmitted222', isSubmitted.value);
	}
);

// 监听 message 变化，重置表单数据和折叠面板状态
watch(
	() => props.message,
	() => {
		// 重置表单数据
		formData.value = {};
		if (fApi.value) {
			fApi.value.resetFields();
		}
	}
);

// 暴露方法给父组件 - 使用 FormCreate API
defineExpose({
	getFormData: () => formData.value,
	validate: () => fApi.value?.validate(),
	submit: () => fApi.value?.submit(),
	setRule: (newRule: any[]) => {
		rule.value = newRule;
	},
	resetFields: () => {
		formData.value = {};
		fApi.value?.resetFields();
	},
});
</script>
